#coding:utf-8
"""
新增服务器信息
"""
import database
import web
import public

#db=database.database()
#db.init_database()
#cursor=db.execute("INSERT INTO servicer (place,system,project,sa,ip,comment,type) VALUES (1,1,1,1,'1.1.1.1:1.1.1.2','this is comment',1)")
#cursor=db.execute('''select place.place,project.project,sa.sa,system.system,type.type from servicer
#  inner join place on servicer.place = place.id
#  inner join project on servicer.project = project.id
#  inner join sa on servicer.sa = sa.id
#  inner join system on servicer.system = system.id
#  inner join type on servicer.type = type.id
#  ''')
#db.commit()
#cursor=db.insert_type('ftp')
#if cursor:
#    print len(cursor.fetchall())
#    for row in cursor:
#        for info in row:
#            print info
#        print '*'*10
#db.close()


class main():
    def __init__(self):
        self.db=database.database()
        self.render=public.render

    @public.catch_exception
    @public.check_login
    def GET(self):
        baseinfos=self.get_baseinfos()
        return self.render.new_servicer(baseinfos=baseinfos)

    @public.catch_exception
    @public.check_login
    def POST(self):
        """处理表单"""
        input_infos=self.get_input_infos()
        sql=r'''INSERT INTO servicer (loginstr,place,system,project,sa,ip,comment,type)
                VALUES ('%s',%s,%s,%s,%s,'%s','%s',%s)
                '''%(input_infos['loginstr'],
                    input_infos['place'],
                    input_infos['system'],
                    input_infos['project'],
                    input_infos['sa'],
                    input_infos['ip'],
                    input_infos['comment'],
                    input_infos['type'],)
        self.db.execute(sql)
        self.db.commit()
        web.seeother('/')

    def get_input_infos(self):
        """整理表单提交的数据"""
        user_input=web.input()
        user_input_default={'loginstr':'',
                            'comment':'',
                            'ip':'',}
        user_input_default.update(user_input)
        user_input=user_input_default
        #表单里的ip是按行分割的，这里去除空行，然后按":"分割。
        ips=user_input['ip'].splitlines()
        ips=[ip.strip() for ip in ips if ip.strip()!='']
        user_input['ip']=':'.join(ips)
        return user_input


    def get_baseinfos(self):
        """获取基本信息，如机房位置等,用于生成表单的选择列表"""
        infos={}
        places=self.db.execute(r"select place.id,place.place from place").fetchall()
        projects=self.db.execute(r"select project.id,project.project from project").fetchall()
        sas=self.db.execute(r"select sa.id,sa.sa from sa").fetchall()
        systems=self.db.execute(r"select system.id,system.system from system").fetchall()
        types=self.db.execute(r"select type.id,type.type from type").fetchall()
        infos['places']=places
        infos['projects']=projects
        infos['sas']=sas
        infos['systems']=systems
        infos['types']=types
        return infos


